import os
import calendar

from datetime import datetime

from google.appengine.ext import db
from google.appengine.ext.webapp import template

from model import Exposition, Picture

from tools import manager

class ExpositionManager(manager.Manager):
    """
    """

    def get_exposition_key(self, title):
        """
        """
        #
        query = Exposition.all()
        query.filter('language =', self.language)
        query.filter('title =', title)
        # try to ge the first
        if query.count() == 0:
            query = Exposition.all()
            query.filter('language =', self.language)
            query.order('title')

        # get the exposition
        exposition = query.get()
        if exposition:
            return exposition.key()

        else:
            return None

    def get_default_exposition(self):
        # find the default author
        exposition_query = Exposition().all()
        exposition_query.filter('language =', self.language)
        exposition_query.filter('title =', ' ')
        # get the default
        exposition = exposition_query.get()
        # if no default we create one
        if not exposition:
            exposition_key = self.new()
            exposition = Author().get(exposition_key)
        #return the default author
        return exposition

    def get_menu(self, edit=False):
        """
        """
        # get all expositions
        query = Exposition.all()
        query.filter('language =', self.language)
        query.order('-date_start')
        query.order('title')

        # init menu
        menu = list()

        # list of expositions for a category
        list_expositions = list()

        # current_year init
        current_year = query.get().date_start.year

        # set the menu content
        for exposition in query:

            # test the current char
            if not exposition.date_start.year == current_year \
            and len(list_expositions) > 0:

                # set a dict with the char and corresponding name list
                item_year = {
                            'year': current_year,
                            'expositions': list_expositions}

                # add the dict into the menu
                menu.append(item_year)

                #
                current_year = exposition.date_start.year

                # list of expositions for a category
                list_expositions = list()

            title = exposition.title.strip()
            if title == '':
                if edit:
                    #
                    list_expositions.append(exposition)
                else:
                    pass
            else:
                #
                list_expositions.append(exposition)

        if len(list_expositions) > 0:
            # set a dict with the char and corresponding name list
            item_year = {
                        'year': exposition.date_start.year,
                        'expositions': list_expositions}

            # add the dict into the menu
            menu.append(item_year)

        # return the menu at the end
        return menu

    def show(self, exposition_key=None):
        """
        """
        # 0035693852540
        if not exposition_key:
            #
            exposition_key = self.new()

        # get the menu at first
        menu = self.get_menu()
        #
        exposition = Exposition().get(exposition_key)
        # update max size
        if exposition.html_info:
            exposition.html_info = exposition.html_info.replace('max_size=',
                    'max_size=%s' % self.size.width)

        # get the dates
        date_start = exposition.date_start.strftime('%d/%m/%y')
        date_end = exposition.date_end.strftime('%d/%m/%y')

        # set the template for edit
        self.template_values['action'] = 'exposition'
        self.template_values['menu'] = menu
        self.template_values['exposition'] = exposition
        self.template_values['date_start'] = date_start
        self.template_values['date_end'] = date_end

        # find the template
        path = os.path.join(os.path.dirname(__file__),
                                '../templates', 'exposition', 'index.html')

        # display the page
        return template.render(path, self.template_values)

    def edit(self, exposition_key):
        """
        """
        # get the menu at first
        menu = self.get_menu(edit=True)

        # get the exposition
        exposition = Exposition().get(exposition_key)

        date_start = exposition.date_start
        days_date_start = calendar.monthcalendar(
                date_start.year, date_start.month)

        date_end = exposition.date_end
        days_date_end = calendar.monthcalendar(
                date_end.year, date_end.month)

        # add junk row for nice display
        if len(days_date_start) > len(days_date_end):
            days_date_end.append(
                    [0, 0, 0, 0, 0, 0, 0])
        # add junk row for nice display
        if len(days_date_start) < len(days_date_end):
            days_date_start.append(
                    [0, 0, 0, 0, 0, 0, 0])

        # set some variables for the different calendars
        calendars = [
                {
                    'type': 'date_start',
                    'title': 'Date start',
                    'value': date_start.strftime('%d/%m/%y'),
                    'year': date_start.year,
                    'month': date_start.strftime('%B'),
                    'days': days_date_start,
                },
                {
                    'type': 'date_end',
                    'title': 'Date end',
                    'value': date_end.strftime('%d/%m/%y'),
                    'year': date_end.year,
                    'month': date_end.strftime('%B'),
                    'days': days_date_end,
                    }
                ]

        # set the template for edit
        self.template_values['menu'] = menu
        self.template_values['exposition'] = exposition
        self.template_values['calendars'] = calendars
        self.template_values['page'] = 'exposition'
        self.template_values['images'] = self.get_content_images()

        # find the template
        path = os.path.join(os.path.dirname(__file__),
                            '../templates', 'exposition', 'edit.html')

        # display the author
        return template.render(path, self.template_values)

    def new(self):
        """
        """
        # create the new exposition
        exposition = Exposition()

        # requirement title
        exposition.title = db.Category(' ')

        # requirement date
        year = datetime.today().year
        exposition.date_start = datetime(year, 1, 1)
        exposition.date_end = datetime(year, 1, 1)

        # set the language
        exposition.language = self.language

        #
        exposition.put()

        return exposition.key()

    def delete(self, exposition_key):
        """
        """
        #
        exposition = Exposition().get(exposition_key)

        # get corresponding pictures
        query = Picture().all()
        query.filter('exposition =', exposition)

        # delete relation from picture
        for picture in query:
            picture.exposition = None
            picture.put()

        # delete the page
        exposition.delete()

    def save(self, exposition_key, title, info):
        """
        """
        #
        exposition = Exposition().get(exposition_key)

        # title can't be empty
        title = title.strip()
        if title == '':
            title = ' '
        # set the title
        exposition.title = db.Category(title)

        # set info
        exposition.info = info
        exposition.html_info = self.get_html_content(info)

        # save page
        exposition.put()

    def save_date_year(self, exposition_key, type_start=True, up=True):
        """
        """
        # get the current exposition
        exposition = Exposition().get(exposition_key)

        # work on the date_start
        if type_start:
            date = exposition.date_start

        # work on the date_end
        else:
            date = exposition.date_end

        # add one year
        if up:
            year = date.year + 1

        # less one year
        else:
            year = date.year - 1

        # set the new date
        new_date = datetime(year, date.month, date.day)

        # update the date
        self.__save_date(exposition_key, new_date, type_start=type_start)

    def save_date_month(self, exposition_key, type_start=True, up=True):
        """
        """
        # get the current exposition
        exposition = Exposition().get(exposition_key)

        # work on the date_start
        if type_start:
            date = exposition.date_start

        # work on the date_end
        else:
            date = exposition.date_end

        # add one month
        if up:
            # case of december
            if date.month == 12:
                month = 1
                year = date.year + 1

            # normal case
            else:
                month = date.month + 1
                year = date.year

        # less one year
        else:
            # case of jannuary
            if date.month == 1:
                month = 12
                year = date.year - 1

            # normal case
            else:
                month = date.month - 1
                year = date.year

        # set the new date
        new_date = datetime(year, month, date.day)

        # update the date
        self.__save_date(exposition_key, new_date, type_start=type_start)

    def save_date_day(self, exposition_key, day, type_start=True):
        """
        """
        # get the current exposition
        exposition = Exposition().get(exposition_key)

        # work on the date_start
        if type_start:
            date = exposition.date_start

        # work on the date_end
        else:
            date = exposition.date_end

        # set the new date
        new_date = datetime(date.year, date.month, int(day))

        # update the date
        self.__save_date(exposition_key, new_date, type_start=type_start)

    def save_date_from_str(self, exposition_key, date, type_start=True):
        """
        """
        try:
            # get the datetime object
            formated_datetime = datetime.strptime(date, "%d/%m/%y")
            self.__save_date(exposition_key, formated_datetime, type_start=type_start)
        except:
            pass

    def __save_date(self, exposition_key, date, type_start=True):
        """
        """
        #
        exposition = Exposition().get(exposition_key)

        if type_start:
            # little check
            if date < exposition.date_end:
                # set the date
                exposition.date_start = date

                # save page
                exposition.put()

        else:
            # little check
            if date > exposition.date_start:
                # set the date
                exposition.date_end = date

                # save page
                exposition.put()
